package com.xuecheng.order.service;

import com.xuecheng.framework.domain.task.XcTask;
import com.xuecheng.framework.domain.task.XcTaskHis;
import com.xuecheng.order.dao.XcTaskHisRepository;
import com.xuecheng.order.dao.XcTaskRepository;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class TaskService {

    @Autowired
    XcTaskRepository xcTaskRepository;
    @Autowired
    XcTaskHisRepository xcTaskHisRepository;
    @Autowired
    RabbitTemplate rabbitTemplate;
    //获取指定时间之前的任务列表
    public List<XcTask> findTaskList(Date date,int size){
        Pageable pageable= new PageRequest(0,size);
     Page<XcTask>  all= xcTaskRepository.findByUpdateTimeBefore(pageable,date);
     List<XcTask> xcTaskList=all.getContent();
     return xcTaskList;
    }

    //向rabbitMq发送消息队列
    @Transactional
    public void publish(XcTask xcTask,String ex,String routingKey){
        Optional<XcTask> option = xcTaskRepository.findById(xcTask.getId());
        if(option.isPresent()){
         XcTask task=option.get();
            rabbitTemplate.convertAndSend(ex,routingKey,xcTask);
            task.setUpdateTime(new Date());
            xcTaskRepository.save(task);
        }
    }

    //乐观锁方法校验
    @Transactional
    public int getTask(String taskId,int version){
        int i = xcTaskRepository.updateTaskVersion(taskId, version);
        return i;
    }

    @Transactional
    public  void  finishTask(String taskId){
        Optional<XcTask> taskOptional = xcTaskRepository.findById(taskId);
        if(taskOptional.isPresent()){
            XcTask xcTask = taskOptional.get();
            xcTask.setDeleteTime(new Date());
            XcTaskHis xcTaskHis = new XcTaskHis();
            BeanUtils.copyProperties(xcTask, xcTaskHis);
            xcTaskHisRepository.save(xcTaskHis);
            xcTaskRepository.delete(xcTask);
        }
    }

}
